// src/app.tsx
import { observer } from 'mobx-react-lite';
import React, { PropsWithChildren, useEffect } from 'react';
import { useDidShow, useDidHide, pxTransform } from '@tarojs/taro';
import './assert/taro-ui.css';
import './app.less';
import store from './store';
import Taro from '@tarojs/taro';
import { getCityListFun } from './common/method/commonFun';
import { getAccessTokenFun, userInfoFun } from './common/method/loginFun';
import {
  markNeedUpdateOnLaunch,
  onAppHideSnapshotAuth,
  onAppShowCheckLocation,
} from './utils/locationDelta';

const App: React.FC<PropsWithChildren> = ({ children }) => {
  Taro.setStorageSync('client_id', 'wpmkulfignec');
  Taro.setStorageSync('client_secret', 'VrK2!cW1IDs3f_');
  //获取用户登录状态
  if (Taro.getStorageSync('access_token_login') === '') {
    // Taro.navigateTo({ url: '/subPagesAuth/login/index' });
  }

  // 启动时拍一张“快照”，避免一上来就当变化处理
  markNeedUpdateOnLaunch();

  // 刷新token
  const refreshToken = () => {
    const data: any = {
      client_id: 'wpmkulfignec',
      client_secret: 'VrK2!cW1IDs3f_',
      grant_type: 'refresh_token',
      refresh_token: Taro.getStorageSync('refresh_token_login'),
    };
    getAccessTokenFun(data).then((res: any) => {
      console.log(res, '刷新token成功====');
      Taro.setStorageSync('access_token_login', res.access_token);
      Taro.setStorageSync('refresh_token_login', res.refresh_token);
    });
  };

  const getUserInfo = (res: any) => {
    userInfoFun({
      access_token: res,
    }).then((res: any) => {});
  };
  //获取应用级token
  const getToken = () => {
    const data: any = {
      client_id: 'wpmkulfignec',
      client_secret: 'VrK2!cW1IDs3f_',
      grant_type: 'client_credentials',
    };
    getAccessTokenFun(data)
      .then((res:any) => {
        Taro.setStorageSync('access_token', res);
        store.commonStore.setAccessToken(res);
        console.log(res, 'access_token===========');
        //查询个人信息
        // refreshToken();
      })
      .catch((err) => {
        console.log(err, 'err======');
      });
  };
  useEffect(() => {
    console.log(Taro.getLaunchOptionsSync().scene, 'sence========');
    // 1.获取微信小程序的accessToken
    // Taro.request({
    //   url: 'https://api.weixin.qq.com/cgi-bin/token',
    //   method: 'GET',
    //   data: {
    //     appid: 'wx7042c1d52ab35d54',
    //     secret: '70b9fdbd238f41f6bff599a79639de4b',
    //     grant_type: 'client_credential',
    //   },
    // }).then((res: any) => {
    //   console.log(res, res.access_token, 'res======access_token');
    // });
    //获取应用级token
    getToken();
    // 1. 取系统信息
    const sys = Taro.getSystemInfoSync() as any;
    console.log(sys, 'sys========');
    // 2. 状态栏高度（px）
    const statusBarPx: number = sys.statusBarHeight;

    // 3. 设计里预留的状态栏高度（px）
    // const designReservedTopPx = 44;

    // 4. 顶部真正要用的距离 = max(设备状态栏, 设计预留)
    // const topPx = Math.max(statusBarPx, designReservedTopPx);

    // 5. 导航栏高度（设计稿里是固定 44px）
    const navBarPx = 44;

    // 6. 底部安全区（iOS 底部手势栏）：优先取 safeAreaInsets.bottom，否则自己算
    let bottomInsetPx = 0;
    if (sys.safeAreaInsets && typeof sys.safeAreaInsets.bottom === 'number') {
      bottomInsetPx = sys.safeAreaInsets.bottom;
    } else if (sys.safeArea) {
      bottomInsetPx = sys.screenHeight - sys.safeArea.bottom;
    }

    // 7. 把 px 转成 rpx，并取出数字部分
    const safeAreaTopRpx = parseFloat(pxTransform(statusBarPx));
    const pageAreaTopRpx = parseFloat(pxTransform(statusBarPx + navBarPx));
    const safeAreaBottomRpx = parseFloat(pxTransform(bottomInsetPx));

    console.log(
      'statusBarPx, safeTopRpx, pageTopRpx, safeBottomRpx:',
      statusBarPx,
      safeAreaTopRpx,
      pageAreaTopRpx,
      safeAreaBottomRpx,
      statusBarPx,
      navBarPx
    );

    // 8. 存进 store（数值，单位都是 rpx）
    store.commonStore.setSafeAreaTop(safeAreaTopRpx);
    store.commonStore.setPageAreaTop(pageAreaTopRpx);
    store.commonStore.setSafeAreaBottom(safeAreaBottomRpx);
    //判断设备是ios还是android
    if (sys.platform === 'ios') {
      store.commonStore.setIsIos(true);
    } else {
      store.commonStore.setIsIos(false);
    }
  }, []);

  useEffect(() => {
    //获取当前页面路由参数，微信小程序的scene
    const pages: any = Taro.getCurrentPages();
    const currentPage = pages[pages.length - 1];
    console.log(currentPage, 'currentPage======');
    // 只在微信小程序环境下开启 vConsole
    if (process.env.TARO_ENV === 'weapp') {
      Taro.setEnableDebug({ enableDebug: true }) //调试模式开启/关闭 true/false
        .then((res) => {
          console.log('vConsole 已开启', res.errMsg);
        })
        .catch((err) => {
          console.warn('vConsole 开启失败', err);
        });
    }
    getCityListFun()
      .then((res: any) => {
        Taro.setStorageSync('cityList', res);
      })
      .catch(console.error);
  }, []);

  // Taro 小程序切到前台时触发，等同 componentDidShow
  useDidShow(() => {
    onAppShowCheckLocation();
  });

  // Taro 小程序切到后台时触发，等同 componentDidHide
  useDidHide(async () => {
    await onAppHideSnapshotAuth();
  });
  // 渲染页面组件
  return <>{children}</>;
};

export default observer(App);
